#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import datetime
from django.utils import simplejson
import cgi

from model import Lecture
from model import Topic

class MyHandler(webapp.RequestHandler):
    
    # Receives course or question, returns an array with the questions
    def get(self):
        form = cgi.FieldStorage()

        if form.getvalue("lectureKey") == None:
            return
        
        lecture = Lecture.get(form.getvalue("lectureKey"))

        topics = db.Query(Topic).filter('lecture =', lecture).order('index')
        topicsObj = []
        for t in topics:
            obj = { "name": t.name, "index":t.index, "time":t.time, "key":str(t.key())}
            topicsObj.append(obj)
        
        values = {
            "lectureId" : lecture.key(),
            "lectureName" : lecture.name,
            "topics" : topicsObj
        }
        # self.response.out.write(simplejson.dumps(lecturesObj))
        self.response.out.write(template.render('template/lecture.html', values))
                            
def main():
    app = webapp.WSGIApplication([
        (r'.*', MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()